package com.itheima.juc23.question2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author li
 */
public class MyRunnable implements Runnable {
    // 礼品数
    private int count;
    // 锁
    private final Lock lock = new ReentrantLock();

    public MyRunnable(int count) {
        this.count = count;
    }

    @Override
    public void run() {
        while (count >= 10) {
            lock.lock();
            try {
                if (count < 10) {
                    System.out.println("当前" + Thread.currentThread().getName() + "在送礼物，礼品数为：" + count + "，不再送出");
                    break;
                } else {
                    Thread.sleep(100);
                    count--;
                    System.out.println(Thread.currentThread().getName() + "送出一份礼品，剩余礼品数：" + count);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }
}
